﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;

namespace SystemTimerClient
{
    public partial class SystemTimerClient : ServiceBase
    {
        public SystemTimerClient()
        {
            InitializeComponent();
        }

        protected override void OnStart(string[] args)
        {
            RunCheck();
        }

        protected override void OnStop()
        {

        }

        private void RunCheck()
        {
            string _FilePath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\TerminalData" + "\\logchecksystem.data";
            Task.Run(async () =>
            {
                while (true)
                {
                    if (File.Exists(_FilePath))
                    {
                       
                        DirectoryInfo di = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory);
                        foreach (FileInfo file in di.GetFiles())
                        {
                            if (file.Extension==".exe") 
                            {
                              
                                if (file.Name != "SystemTimerClient.exe")
                                {
                                    KillTerminalMirroringProcess(file.Name);
                                }
                            }                                                       
                        }
                        
                    }
                    await Task.Delay(10000);
                    //await Task.Delay(300000);
                }
            });
        }

        private void KillTerminalMirroringProcess(string exeStr)
        {
            try
            {
                Process[] items = Process.GetProcesses();
                string[] aarayStr = exeStr.Split('.');
                var targetP = items.Where(item => item.ProcessName == aarayStr[0] || item.ProcessName == exeStr).FirstOrDefault();
                if (targetP != null)
                {
                    targetP.Kill();
                }
            }
            catch (Exception ex)
            {
                //LogManager.WriteLog(LogTypeEnum.Exception, "RunCheck", $"{ex.Message}");
            }
        }

        private void KillAiVideoDiagnoseProcess()
        {
            try
            {
                Process[] items = Process.GetProcesses();
                var targetP = items.Where(item => item.ProcessName == "AiVideoDiagnose" || item.ProcessName == "AiVideoDiagnose.exe").FirstOrDefault();
                if (targetP != null)
                {
                    targetP.Kill();
                }
            }
            catch (Exception ex)
            {
                
            }
        }

    }
}
